// pages/Order/showTicketOrder/index.js
const common = require('../../../public.js')
const config = require('../../../config')
const utils = require('../utils.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabbarActive: 2,
    titles: 0, //订单来源
    actives: 0,
    pageNum: 1,
    status: '0', // ' '=全部 ，1、未付款，2、已付款，5、交易成功，6、交易关闭
    orderList: [],
    refreshing: false,
    isLoadingBusy: false,
    isFyApp: config.isFyApp,
    active: 4,
    storeId: 0,
    moduleType: 1,
    tabshow: false,
    show: false,
    Bigimgs: '',
    coupList:[]
  },
  
  goBack() {
    const pages = getCurrentPages();
    const prevPage = pages[pages.length - 2]; //上一个页面
    // 从朋友圈进入的时候，页面栈为空，这里需要判断是否有上个页面
    if (prevPage) {
        wx.navigateBack({
            delta: 1
        })
    } else {
        wx.redirectTo({
            url: '/pages/index/index',
        })
    }
},

  // 去卡包
  toCardPack() {
    this.setData({
      tabbarActive: 4
    })
    wx.redirectTo({
      url: '/packageC/pages/packCard/packCard',
    })
  },
  toIndex() {
    wx.redirectTo({
      url: '/packageA/pages/indexnian/indexni',
    })
  },
  // 查看物流
  Toexpress(e) {
    let {
      expressNumber,
      picPath,
      expressCompany
    } = e.currentTarget.dataset.item
    wx.navigateTo({
      url: '/packageB/pages/express/express?expressNumber=' + expressNumber +
        '&storeImage=' + picPath + '&expressCompany=' + expressCompany,
    })
  },
  // 会员卡商品
  payNow(e) {
    const item = e.currentTarget.dataset.item
    const that = this
    const tempJson = {
      userId: that.data.userInfo.id,
      token: that.data.token,
      orderId: item.orderId,
      // openid: that.data.openid,
      xcxOpenid: that.data.openid,
    }
    // common.wxPayRequest('/wxxcxPayForGoods', tempJson, function (res) {
    common.wxPayRequest('/wxxcxPayGoodsForChinaUms', tempJson, function (res) {
      if (res.status === 200) {
        //微信支付
        wx.requestPayment({
          'timeStamp': res.data.timeStamp,
          'nonceStr': res.data.nonceStr,
          'package': res.data.package,
          'signType': res.data.signType,
          'paySign': res.data.paySign,
          'success': function (res) {
            common.showToast('支付成功', 'success')
            that.reloadData()
          },
          'fail': function (res) {
            console.log('微信支付res为', res);
            if (res.errMsg === 'requestPayment:fail cancel') {} else {
              common.showToast(res.errMsg)
            }
          }
        })
      }
    })
  },
  // 评价
  toComment(e) {
    // const item = e.currentTarget.dataset.item
  
    // wx.navigateTo({
    //   url: '/pages/comment/index?orderId=' + item.orderId,
    // })
    let {
        item
      } = e.currentTarget.dataset
      console.log(item)
      wx.navigateTo({
        url: '/pages/ScenicArea/NianCardOrder/Cardcomment/Cardcomment?storeId='
         + item.storeId + 
         '&orderNo=' + item.orderNo + 
          '&flag=1'
         ,
      })
  },
  click_imgs(e) {
    console.log(e.currentTarget.dataset.item.picPath)
    this.setData({
      show: true,
      Bigimgs: e.currentTarget.dataset.item.picPath
    })
    //  放大图片
  },
  onClickShow() {
    this.setData({
      show: true
    });
  },

  onClickHide() {
    this.setData({
      show: false
    });
  },

  noop() {},
  // 确认收货
  confirm(e) {
    const item = e.currentTarget.dataset.item
    const that = this
    const param = {
      userId: that.data.userInfo.id,
      token: that.data.token,
      orderId: item.orderId
    }
    common.post('/order/confirm', param, function (res) {
      if (res.status === 200) {
        common.showToast('确认收货成功', 'success')
        that.reloadData()
      } else {
        common.showRequestErrMsg(res)
      }
    })
  },
  ontitle(event) {
    var index = event.detail.name
    console.log(index,"index.....")
    this.setData({
      titles: index
    }, () => {
      this.reloadData()
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  // 删除按钮点击事件
  onDelete(e) {
    const orderId = e.currentTarget.dataset.item.orderId
    const that = this
    common.showAlertView('提示', '是否删除该订单？', function (res) {
      if (res) {
        that.submitDelete(orderId)
      }
    })
  },
  // 提交删除事件
  submitDelete(orderId) {
    const that = this
    common.post('/order/delete', {
        orderId,
        userId: that.data.userInfo.id,
        token: that.data.token
      },
      function (res) {
        if (res.status == 200) {
          common.showToast('删除成功！')
          that.reloadData()
        } else {
          common.showRequestErrMsg(res)
        }
      })
  },
  cancelOrder(e) { // 取消订单
    const that = this
    common.showAlertView('提示', '是否取消该订单', function (res) {
      if (res) {
        let orderId = e.currentTarget.dataset.item.orderNo
        console.log(orderId)
        let tempJson = {
          userId: that.data.userInfo.id,
          token: that.data.token,
          orderNo: orderId
        }
        common.post('/ticketOrder/cancleTicketOrder', tempJson, function (res) {
          if (res.status === 200) {
            common.showToast('已取消订单')
            that.reloadData()
          } else {
            common.showRequestErrMsg(res)
          }
        })
      }
    })
  },
  // 取消订单
  cancelOrders(e) {
    const that = this
    common.showAlertView('提示', '是否取消该订单', function (res) {
      if (res) {
        let orderId = e.currentTarget.dataset.item.orderId
        let tempJson = {
          userId: that.data.userInfo.id,
          token: that.data.token,
          orderId: orderId
        }
        common.post('/order/cancel', tempJson, function (res) {
          if (res.status === 200) {
            common.showToast('已取消订单')
            that.reloadData()
          } else {
            common.showRequestErrMsg(res)
          }
        })
      }
    })
  },
  // 跳转评价
  goComent(e) {
    let {
      item
    } = e.currentTarget.dataset
    console.log(item)
    wx.navigateTo({
      url: '/pages/ScenicArea/NianCardOrder/Cardcomment/Cardcomment?storeId='
       + item.storeId + 
       '&orderNo=' + item.orderNo + 
        '&flag=0'
       ,
    })
  },
  onLoad: function (options) {
    const that = this
    //获取胶囊位置
    let capsule = wx.getMenuButtonBoundingClientRect()
    this.setData({
      height: capsule.height,
      top: capsule.top,
    })
    var windowHeight = wx.getSystemInfoSync().windowHeight
    var windowWidth = wx.getSystemInfoSync().windowWidth
    this.setData({
      scroll_height: windowHeight * 750 / windowWidth - 200
    })

    if (options.titles) {
      //  var titles =
      that.setData({
        titles: parseInt(options.titles)
      })
    }
    if (options.status) {
      console.log(options)
      that.setData({
        status: options.status,
        actives: options.status
      })
      if (options.id) {
        this.data.storeId = options.id ? options.id : config.id
        this.data.moduleType = options.moduleType ? options.moduleType : config.type
        this.setData({
          tabshow: true
        })
      }


    }

    wx.getStorage({
      key: 'user',
      success: function (res) {
        that.setData({
          userInfo: res.data.user,
          token: res.data.token,
          openid: res.data.openid
        }, () => {
          that.reloadData()
        })
      }
    })
  },
  onChangeTabbar(e) { //切换底部导航
    const index = e.detail.index
    const url = e.detail.url
    if (index != this.data.active) {
      utils.onChangeTabbar(url, this.data.storeId, this.data.moduleType)
    }
  },

  getOrderList(refresh = false) {
    const that = this
    // 当前正在加载或没有获取到用户信息，不再加载数据
    if (this.data.isLoadingBusy || !this.data.userInfo) {
      return
    }
    // 是否是在切换tab页，切换tab页不显示下拉刷新提示
    if (refresh) {
      this.setData({
        noMoreData: false,
        refreshing: true,
        isLoadingBusy: true
      })
    } else {
      if (this.data.noMoreData === true) {
        return
      }
      this.setData({
        isLoadingBusy: true,
        refreshing: false
      })
    }

    const pageNum = refresh ? 1 : this.data.pageNum + 1
    var tempJson
    var url
    if (this.data.titles == 1) {
      url = '/ticketOrder/getMyTicketOrderList'
      tempJson = {
        userId: that.data.userInfo.id,
        token: that.data.token,
        pageNum: pageNum,
        pageSize: 10,
        orderType: 1, //会员卡1
        status: that.data.status == 0 ? '' : that.data.status,
      }
    } else if(this.data.titles == 0){
      url = '/order/cardItemList',
        tempJson = {
          userId: that.data.userInfo.id,
          status: that.data.status == 0 ? 0 : that.data.status,
          token: that.data.token,
          pageNum: pageNum,
          // pageSize: 10,
          orderType: 1, //会员卡1
        }
    }else{
      url = '/cardCoupon/getCardCouponOrderList',
      tempJson = {
        userId: that.data.userInfo.id,
        status: that.data.status == 0 ? '' : that.data.status,
        token: that.data.token,
        pageNum: pageNum,
        pageSize: 10,
        // orderType: 1, //会员卡1
      }
    }

    common.post(url, tempJson, function (res) {
        if (res.status == 200) {
          // 更新页码
          if (res.data === null || res.data.length === 0) {
            that.setData({
              noMoreData: true,
            }, () => {
              console.log(that.data.orderLists, "数组为零")
            })
          }
        } else {
          if(pageNum==1){
            common.showRequestErrMsg(res)
          }else{
            common.showToast('已经到底啦')
          }
         
        }
        let orderLists = []
        that.data.pageNum = pageNum
        if (that.data.titles == 1 ) {
          that.setData({
            orderList: refresh ? res.data : [...that.data.orderList, ...res.data]
          }, () => {
           
          })
        } else if(that.data.titles == 0){
          if (res.data) {
            for (var i = 0; i < res.data.length; i++) {
           
              var twoList = res.data[i].list;
              var totalNum = 0;
                for (var j = 0; j < twoList.length; j++) {
                    totalNum =twoList[j].num + totalNum;
                }
                res.data[i].list[0].num = totalNum;
                orderLists.push(res.data[i].list[0])
            }
          }
          that.setData({
            orderLists: refresh ? orderLists : [...that.data.orderLists, ...orderLists]
          }, () => {
           
          })
        }else{
          that.setData({
            coupList: refresh ? res.data : [...that.data.coupList, ...res.data]
          }, () => {
           
          })
        }


      },
      function () {

        that.setData({
          isLoadingBusy: false
        })
        if (refresh) {
          that.setData({
            refreshing: false
          })
        }
      })
  },

  watchEticket(e) {
    let {
      item
    } = e.currentTarget.dataset
    //  console.log(e.currentTarget.dataset)
    wx.navigateTo({
      url: '/pages/ScenicArea/CardETicket/index?orderNo=' + item.orderNo,
    })
  },
  toOrderDetail(e) {
    let {
      item
    } = e.currentTarget.dataset
    wx.navigateTo({
      url: '/pages/ScenicArea/CardOrderDetail/index?orderNo=' + item.orderNo + '&obj=' + '3' +
        '&flag=' + 6
    })
  },
  payOrder: common.throttleFunc(function (e) {
    const that = this
    console.log(e)
    let {
      item
    } = e.currentTarget.dataset

    let tempJson = {
      orderId: item.id,
      userId: that.data.userInfo.id,
      token: that.data.token,
      // openid: that.data.openid
      xcxOpenid: that.data.openid
    }
    // common.wxPayRequest('/wxxcxPayForScenicTicket', tempJson, function (res) {
      common.wxPayRequest("/wxxcxPayScenicTicketForRegionWLByChinaUms", tempJson, function (res) {
      wx.requestPayment({
        'timeStamp': res.data.timeStamp,
        'nonceStr': res.data.nonceStr,
        'package': res.data.package,
        'signType': res.data.signType,
        'paySign': res.data.paySign,
        'success': function (res) {
          common.showToast('支付成功', 'success')
          that.reloadData()
        },
        'fail': function (res) {
          if (res.errMsg === 'requestPayment:fail cancel') {} else {
            common.showToast(res.errMsg)
          }
        }
      })
    })
  }, 1000),
  deleteClosedOrder(e) { // 删除已经关闭订单
    const that = this
    common.showAlertView('提示', '是否删除该订单？', function (res) {
      if (res) {
        let {
          item
        } = e.currentTarget.dataset
        let tempJson = {
          userId: that.data.userInfo.id,
          token: that.data.token,
          orderNo: item.orderNo
        }
        common.post('/ticketOrder/delTicketOrder', tempJson, function (res) {
          if (res.status == 200) {
            common.showToast('删除成功')
            that.reloadData()
          } else {
            common.showRequestErrMsg(res)
          }
        })
      }
    })
  },
  onChange(e) {
    this.data.status = e.detail.name
    this.reloadData(true)
  },
  reloadData() {
    this.setData({
      orderList: [],
    }, _ => {
      this.getOrderList(true)
    })
  },
  loadMore() {
    this.getOrderList(false)
  },
  onReachBottom() {
    console.log("125244545")
    this.getOrderList(false)
  },
  toDetail(e) {
    
    // const item = e.currentTarget.dataset.item
    // console.log(item,"455555555")
    // wx.navigateTo({
    //   url: '/packageA/pages/Goods/goodsOrder/goodsBenafitDetail/index?orderId=' + item.id
    // url:'/packageA/pages/Goods/goodsOrder/detail/index?orderId=' + item.id
   
    // })
    const item = e.currentTarget.dataset.item
    wx.navigateTo({
      url: '/packageA/pages/Goods/goodsOrder/goodsOrderDetail/index?orderId=' + item.orderId
    })
  },
})